package com.winit.cloudlink.mgmt.recovery;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class FileMessageWriter implements MessageWriter, Closeable {
    private static final Logger logger = LoggerFactory.getLogger(FileMessageWriter.class);
    private static final String CHARSET_NAME = "utf-8";
    private static final String KEY_HEADER = "headers";
    private static final String KEY_PAYLOAD = "payload";

    private FastDateFormat df = FastDateFormat.getInstance("yyyy-MM-dd");
    private File outputFile;
    private Writer output;

    public FileMessageWriter(String outputFile) throws IOException {
        this.outputFile = new File(outputFile);
        output = new FileWriter(outputFile);
    }

    public FileMessageWriter(File outputFile) throws IOException {
        this.outputFile = outputFile;
        output = new FileWriter(outputFile);
    }

    public String getOutputFile() {
        return outputFile.getAbsolutePath();
    }

    @Override
    public void write(Message message) {
        try {
            byte[] body = message.getBody();
            String payload = new String(body, CHARSET_NAME);

            Map<String, Object> headers = message.getMessageProperties().getHeaders();

            Map<String, Object> newMessage = new HashMap<String, Object>();
            newMessage.put(KEY_HEADER, headers);
            newMessage.put(KEY_PAYLOAD, payload);

            String messsageJson = JSON.toJSONString(newMessage);
            output.append(messsageJson + "\r\n");
            output.flush();
        } catch (Exception e) {
            logger.error("write error.", e);
        }
    }


    @Override
    public void close() throws IOException {
        if (output != null) {
            output.close();
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        close();
    }

}
